<?php

namespace App\ApiBackend;

use App\Http\Controllers\ApiBaseController;
use App\Models\UserTokenModel;
use Illuminate\Support\Facades\DB;

/**
 *  退出
 */
class Logout extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $token = request()->bearerToken();
    $tokenArr = explode("|", $token);
    $tokenId = (int)$tokenArr[0];
    if (!$token && $tokenId > 0) {
      $this->result['code'] = 1;
      $this->result['message'] = '未登录';
      return;
    }
    //更新最后时间时间
    $tokenInfo = DB::table('user_token')->where('userTokenId', $tokenId)->first(['tokenable_id as adminId', 'tokenable_type', 'updated_at as lastUsedTIme']);
    if ($tokenInfo) {
      DB::table('admin')->where('adminId', $tokenInfo->adminId)->update(['lastLoginTime' => $tokenInfo->lastUsedTIme]);
    }
    DB::table('user_token')->where('userTokenId', $tokenId)->delete();
    $this->result['code'] = 0;
    $this->result['message'] = '退出登录成功';
  }
}
